package com.android.accessibility.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import com.android.accessibility.view.FloatView;

public class FloatService extends Service {

    private WindowManager mWindowManager=null;
    private WindowManager.LayoutParams mLayoutParams=null;

    private FloatView mFloatView = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(1000000, new Notification());
        initLayoutParams();
        createView();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        /*
        if(intent != null){
            String className = intent.getStringExtra("class_name");
            mFloatView.setClass(className);
        }
        */
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(false);
        mWindowManager.removeView(mFloatView);
    }
    private void initLayoutParams(){
        mWindowManager = (WindowManager)getSystemService(Service.WINDOW_SERVICE);
        mLayoutParams = new WindowManager.LayoutParams();
        mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR; // Can be drag to statusbar
        mLayoutParams.format = PixelFormat.RGBA_8888;
        mLayoutParams.alpha = 1.0f;

        mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
                | LayoutParams.FLAG_NOT_FOCUSABLE
                | LayoutParams.FLAG_LAYOUT_IN_SCREEN;

        /**
         * type = LayoutParams.TYPE_SYSTEM_ERROR and flags = LayoutParams.FLAG_LAYOUT_IN_SCREEN
         * can be drag to statusbar
         */
        /*
         mLayoutParams.flags=LayoutParams.FLAG_NOT_TOUCH_MODAL 
                               | LayoutParams.FLAG_NOT_FOCUSABLE
                               | LayoutParams.FLAG_NOT_TOUCHABLE;
         */
        mLayoutParams.gravity=Gravity.LEFT|Gravity.TOP;
        // mLayoutParams.gravity = Gravity.RIGHT | Gravity.TOP;
        DisplayMetrics dm = getResources().getDisplayMetrics();
        mLayoutParams.x = 0;
        mLayoutParams.y = dm.heightPixels / 2;

        mLayoutParams.width = LayoutParams.WRAP_CONTENT;
        mLayoutParams.height = LayoutParams.WRAP_CONTENT;
    }
    private void createView(){
        mFloatView = new FloatView(this);
        mFloatView.setWindowManager(mWindowManager, mLayoutParams);
        mWindowManager.addView(mFloatView, mLayoutParams);
    }
}